package com.ghh.controller;

import com.ghh.domain.User;
import com.ghh.feign.SmsFeign;
import com.ghh.mapper.UserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SmsFeign smsFeign;

    @Autowired
    private UserMapper userMapper;

    //发送验证码
    @GetMapping("/send/{phone}")
    public String sendMessage(@PathVariable("phone")String phone){
        try {
            String message = "13579";
            smsFeign.setSmsToRedis(phone,message);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    //登录
    @PostMapping("/login")
    public String login(String phone,String password,String message){
        //1、获取前台传来的手机号，密码和验证码
        //2、通过手机号在redis中取出验证码进行校验
        //3、验证失败，返回失败，验证成功，继续验证密码

        //校验验证码
        String redisMessage = smsFeign.getSmsToRedis(phone);
        if (StringUtils.isNotEmpty(redisMessage)){//判断redis内是否有值
            if (redisMessage.equals(message)){//判断验证码是否正确
                //通过手机号查询并校验密码
                Example example = new Example(User.class);
                Example.Criteria criteria = example.createCriteria();
                if(StringUtils.isNotEmpty(phone)){
                    criteria.andEqualTo("phone",phone);
                }
                if(StringUtils.isNotEmpty(password)){
                    criteria.andEqualTo("password",password);
                }
                List<User> list = userMapper.selectByExample(example);
                return list.get(0).toString();
            }else {
                return "请输入正确的验证码";
            }
        }else {
            return "请获取验证码后再登录";
        }
    }
}
